package com.qianguo.buyer.tab;

import android.content.Context;
import android.graphics.Paint;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.api.entity.BaseBean;
import com.eva.androidlibrary.icon.FruitIcon;
import com.eva.androidlibrary.utils.IconfontUtil;
import com.eva.androidlibrary.widget.SimpleTagImageView;
import com.eva.androidlibrary.widget.SwipeRefreshRecyclerView;
import com.qianguo.buyer.BuyerLoginActivity;
import com.qianguo.buyer.R;
import com.qianguo.buyer.base.BaseFragment;
import com.qianguo.buyer.constant.BuyerKeys;
import com.qianguo.buyer.entity.AddShopCar;
import com.qianguo.buyer.entity.EventActionBean;
import com.qianguo.buyer.entity.ShopCarItem;
import com.qianguo.buyer.entity.ShopCar;
import com.qianguo.buyer.order.BuyerOrderConfirmActivity;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;

import java.util.List;

import static com.qianguo.buyer.R.id.item_buyer_product_num_text_view;


/**
 * TAB 购物车
 *
 * @author eva
 * @date 16/6/28
 */
@EFragment(R.layout.fragment_shop_car_list)
public class ShopCartFragment extends BaseFragment {

    @ViewById(R.id.rv_shop_car_list)
    SwipeRefreshRecyclerView mShopCarList;

    @ViewById(R.id.buyer_shop_cart_login_button)
    Button mBtnLogin;

    @ViewById(R.id.buyer_shop_cart_total_price_text_view)
    TextView mTvShopCartPrice; // 总价

    @ViewById(R.id.buyer_shop_cart_delivery_price_text_view)
    TextView mTvDeliveryPrice; // 配送费

    @ViewById(R.id.buyer_shop_cart_layout)
    RelativeLayout mRlShopCart;

    @ViewById(R.id.buyer_shop_cart_settle_accounts_layout)
    LinearLayout mRlSettle; // 去结算

    private ShopCar mShopCart;
    private ShopCartAdapter mAdapter;

    @Override
    protected void initializeUI() {
        mRlSettle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BuyerOrderConfirmActivity.jumpToConfirmOrder(getActivity(), "");
            }
        });
        if (!mApp.isLogin()) {
            BuyerLoginActivity.jumpToLogin(getActivity());
        } else {
            mBtnLogin.setVisibility(View.GONE);
            mRlShopCart.setVisibility(View.VISIBLE);
            mAdapter = new ShopCartAdapter(getActivity());
            mShopCarList.setAdapter(mAdapter);
            mShopCarList.setIsLoadMore(false);
            mShopCarList.setSwipeRefreshListener(new SwipeRefreshRecyclerView.SwipeRefreshListener() {
                @Override
                public void onRefresh() {
                    getShopCart();
                }

                @Override
                public void onLoadMore() {
                }
            });
            getShopCart();
        }
    }

    /**
     * 获取购物车列表
     */
    @Background
    void getShopCart() {
        mApp.getApi().getShopCarList(mApp.getUser().getToken(), "", new HttpRequestCallback<ShopCar>() {
            @Override
            public void onSuccess(int code, String msg, ShopCar data) {
                refreshUI(data);
            }


            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(getActivity(), msg);
            }
        });
    }

    /**
     * 修改商品
     */
    @Background
    void editShopCar(int carId, int num) {
        mApp.getApi().editShopCar(mApp.getUser().getToken(), carId, num, 1, new HttpRequestCallback<BaseBean>() {
            @Override
            public void onSuccess(int code, String msg, BaseBean data) {
            }


            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(getActivity(), msg);
            }
        });
    }


    @UiThread(propagation = UiThread.Propagation.REUSE)
    void refreshUI(ShopCar data) {
        mShopCart = data;
        mTvShopCartPrice.setText(data.getNum() + "份，约￥" + data.getTotal_price());
        mShopCarList.onCompleted();
        mShopCarList.notifyDataSetChanged();
    }

    @UiThread(propagation = UiThread.Propagation.REUSE)
    void updateShopCarIds(List<ShopCarItem> goods) {
        EventActionBean bean = new EventActionBean(BuyerKeys.ACTION_UPDATE_CARIDS);
        bean.obj = goods;
        EventBus.getDefault().post(bean);
    }

    private class ShopCartAdapter extends RecyclerView.Adapter<ShopCartViewHolder> {

        private Context mContext;
        private ShopCartAdapter(Context context) {
            mContext = context;
        }

        @Override
        public ShopCartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.item_buyer_product, null);
            RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(
                    RecyclerView.LayoutParams.MATCH_PARENT,
                    RecyclerView.LayoutParams.WRAP_CONTENT);
            v.setLayoutParams(lp);
            return new ShopCartViewHolder(v);
        }

        @Override
        public void onBindViewHolder(ShopCartViewHolder holder, int position) {
            holder.onBind(mShopCart.getGoods().get(position));
        }

        @Override
        public int getItemCount() {
            return mShopCart != null && mShopCart.getGoods() != null ? mShopCart.getGoods().size() : 0;
        }
    }

    private class ShopCartViewHolder extends RecyclerView.ViewHolder {

        ShopCartViewHolder viewHolder;
        SimpleTagImageView imgCover;
        TextView tvProductName;
        TextView tvProductUnit;
        TextView tvMarketPrice;
        TextView tvProductPrice;
        Button btnBuy;
        LinearLayout numLayout;
        TextView tvAdd;
        TextView tvDelete;
        TextView tvNum;

        public ShopCartViewHolder(final View itemView) {
            super(itemView);
            viewHolder = this;
            imgCover = (SimpleTagImageView) itemView.findViewById(R.id.item_buyer_product_cover_image_view);
            tvProductName = (TextView) itemView.findViewById(R.id.item_buyer_product_name_text_view);
            tvProductUnit = (TextView) itemView.findViewById(R.id.item_buyer_product_unit_text_view);
            tvMarketPrice = (TextView) itemView.findViewById(R.id.item_buyer_product_market_price_text_view);
            tvProductPrice = (TextView) itemView.findViewById(R.id.item_buyer_product_price_text_view);
            btnBuy = (Button) itemView.findViewById(R.id.item_buyer_product_buy_button);
            numLayout = (LinearLayout) itemView.findViewById(R.id.item_buyer_product_num_layout);
            tvAdd = (TextView) itemView.findViewById(R.id.item_buyer_product_add_text_view);
            tvDelete = (TextView) itemView.findViewById(R.id.item_buyer_product_minus_text_view);
            tvNum = (TextView) itemView.findViewById(item_buyer_product_num_text_view);

            btnBuy.setVisibility(View.GONE);
            numLayout.setVisibility(View.VISIBLE);
            IconfontUtil.setIcon(getActivity(), tvAdd, FruitIcon.ICON_SHOP_CART_ADD);
            IconfontUtil.setIcon(getActivity(), tvDelete, FruitIcon.ICON_SHOP_CART_MINUS);
        }

        void onBind(final ShopCarItem info) {
            mImageLoader.loadImage(getActivity(), imgCover, info.getImg_url(), R.drawable.default_cover);
            tvProductName.setText(info.getName());
            tvProductUnit.setText(info.getUnit());
            tvMarketPrice.setText("￥" + Float.toString(info.getMarket_price()));
            tvMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            tvProductPrice.setText(Float.toString(info.getPrice()));
            tvNum.setText(Integer.toString(info.getNum()));

            tvAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addShopCart(mApp.getUser().getToken(), info.getProductid(), info.getShopid(), 1, 1, 1);
                }
            });

            tvDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteFromShopCart(info);
                }
            });

        }
    }

    private void deleteFromShopCart(final ShopCarItem item) {
        if (item.getNum() == 1) {
            showDialog(getActivity(), "提示", "您确定删除该商品吗？",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            deleteProduct(item.getCartid());
                        }
                    },
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            closeDialog();
                        }
                    });
        } else {
            deleteShopCart(mApp.getUser().getToken(), item.getCartid(), item.getNum() - 1, 1);
        }
    }


    @Background
    void deleteShopCart(String token, int cartId, int num, int isSelected) {
        mApp.getApi().editShopCar(token, cartId, num, isSelected, new HttpRequestCallback<BaseBean>() {
            @Override
            public void onSuccess(int code, String msg, BaseBean data) {
                getShopCart();
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    /**
     * 刪除商品
     */
    @Background
    void deleteProduct(int carId) {
        showLoadingDialog(getActivity());
        mApp.getApi().deleteShopCar(mApp.getUser().getToken(), carId, new HttpRequestCallback<BaseBean>() {
            @Override
            public void onSuccess(int code, String msg, BaseBean data) {
                getShopCart();
            }


            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(getActivity(), msg);
            }
        });
        closeLoadingDialog();
    }

    /**
     * 添加购物车
     */
    @Background
    void addShopCart(String token, String productID, String shopId, int isLeijia, int isSelected, int num) {
        showLoadingDialog(getActivity());
        mApp.getApi().addShopCar(token, productID, shopId, num, isLeijia, isSelected, new HttpRequestCallback<AddShopCar>() {
            @Override
            public void onSuccess(int code, String msg, AddShopCar data) {
                getShopCart();
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
        closeLoadingDialog();
    }
}
